import { useState } from 'react'
import { Button, Form, Input } from 'antd'
// 自定义
import styles from './index.module.less'
import { Login } from '@/types/api'
import { message } from '@/utils/AntdGlobal'
import api from '@/api'
import { useStore } from '@/store'

export default function LoginFC() {
  const [loading, setLoading] = useState(false)
  const updateToken = useStore(state => state.updateToken)

  const onFinish = async (values: Login.params) => {
    try {
      setLoading(true)
      const data: any = await api.login(values)
      setLoading(false)
      updateToken(data)
      message.success('登录成功')

      const params = new URLSearchParams(location.search)
      setTimeout(() => {
        location.href = params.get('callback') || '/welcome'
      })
    } catch (error) {
      setLoading(false)
    }
  }

  return (
    <div className={styles.login}>
      <Form name='basic' labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} style={{ maxWidth: 600 }} onFinish={onFinish}>
        <Form.Item label='用户名' name='userName' rules={[{ required: true, message: '请输入用户名' }]}>
          <Input />
        </Form.Item>

        <Form.Item label='密码' name='userPwd' rules={[{ required: true, message: '请输入密码' }]}>
          <Input.Password autoComplete='off' />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type='primary' htmlType='submit' block loading={loading}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
